/*!
 *
 * Copyright (c) 2019, zhang jianchun.
 * Released under the MIT License.
 */


export default class media {
  constructor(constraints = {
    /*
     * 约束对象 可以设置精确值[width:640] 理想值 ideal
     * 可接受的值范围和/或想要尽可能接近的值 width: { min: 640, ideal: 1920, max: 1920 },
     */
    audio: {
      sampleSize: 16, //样本数
      channelCount: 2, //声道数
    },
    video: {
      aspectRatio: {
        ideal: 1.777777778, // 16:9比例优先
        frameRate: { max: 30 }, //帧
        facingMode: { exact: "user" }, //设配 自拍摄像头
      }
    }
  }) {
    this.constraints = constraints
    // 屏幕对象
    this.displayMedia = {
      stream: null,
      constraints: this.constraints
    };

    // 摄像头对象
    this.userMedia = {
      stream: null,
      constraints: this.constraints
    };

    /*
     *设配列表 如：相机和麦克风
     *
     */
    this.enumerateDevices = {}


    /*
     * 获取可修改的约束对象
     *
     */
    this.getSupportedConstraints = {}

    this.isgetUserMedia = 'getUserMedia' in navigator.mediaDevices
    this.isgetDisplayMedia = 'getDisplayMedia' in navigator.mediaDevices
    // 有设置更新 触发
    navigator.mediaDevices.ondevicechange = (event)=> {
      this.updateDeviceList();
    }
    this.init()
  }
  updateDeviceList() {
    navigator.mediaDevices.enumerateDevices()
      .then(function(devices) {

      });
  }
  init() {
    // 获取  获取可修改的约束对象
    if (navigator.mediaDevices && navigator.mediaDevices.getSupportedConstraints) {
      this.getSupportedConstraints = navigator.mediaDevices.getSupportedConstraints();
    }
    // 设配列表
    if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
      navigator.mediaDevices.enumerateDevices().then((devices) => {

          let audioList = [],
            videoList = []
          devices.forEach((device)=> {
            let [kind, type, direction] = device.kind.match(/(\w+)(input|output)/i);

            if (kind === "audioinput") {
              audioList.push(device);
            } else if (kind === "videoinput") {
              videoList.push(device);
            }
          });

          this.enumerateDevices.audioList = audioList
          this.enumerateDevices.videoList = videoList
          // console.log(this.enumerateDevices)
        })
        .catch((err) => { 
          this.onError(err)
          // console.log(err.name + ": " + err.message); 
        });
    }


  }
  // 获取媒体
  async getUserMedia(constraints = this.constraints) {
    // if (this.userMedia.stream) {
    //     alert('有已经打开的设配，请先关闭')
    //     return this.userMedia.stream
    // }
    try {
      return this.userMedia.stream = await navigator.mediaDevices.getUserMedia(constraints);
    } catch (e) {
      this.onError(e)
      // console.error('getUserMedia: ', e)
    }
  }
  // 获取屏幕
  async getDisplayMedia(constraints = this.constraints) {
    // if (this.displayMedia.stream) {
    //     alert('有已经打开的设配，请先关闭')
    //     return this.displayMedia.stream
    // }
    try {
      return this.displayMedia.stream = await navigator.mediaDevices.getDisplayMedia(constraints);
    } catch (e) {
      this.onError(e)
    }
  }

  /*
   * 调整约束
   * track 轨道
   * constraints 要设置的属性对象
   *
   */
  applyConstraints(track, constraints = {}) {
    track.applyConstraints(constraints);
  }

  /*
   * 获取用户设置约束属性的值
   *
   */
  getSettings(track) {
    return track.getSettings();
  }

  /*
   * 获取可约束属性
   *
   */
  getConstraints(track) {
    return track.getConstraints();
  }
  /*
   * 关闭
   *
   */
  stop(stream) {
    if (!stream) return
    stream.getTracks().forEach(track => {
      track.stop();
    });
    stream = null
  }
  /*
   *关闭user
   */
  stopUserMedia() {
    this.stop(this.userMedia.stream)
  }
  /*
   *单独关闭user音频
   */
  stopUserMediaAudio() {
    this.userMedia.stream.getAudioTracks().forEach(track => {
      track.stop();
    });
  }
  /*
   *单独关闭user视频
   */
  stopUserMediaVideo() {
    this.userMedia.stream.getVideoTracks().forEach(track => {
      track.stop();
    });
  }
  /*
   *关闭Display
   */
  stopDisplayMedia() {
    this.stop(this.displayMedia.stream)
  }
  /*
   *关闭Display音频
   */
  stopDisplayMediaAudio() {
    this.displayMedia.stream.getAudioTracks().forEach(track => {
      track.stop();
    });
  }
  /*
   *关闭Display视频
   */
  stopDisplayMediaVideo() {
    this.displayMedia.stream.getVideoTracks().forEach(track => {
      track.stop();
    });
  }

  iofo() {
    this.userMedia.stream.getTracks().forEach(track => {
      console.log(track)
    })
  }
  close(){
    if(this.displayMedia.stream)this.stopDisplayMedia()
    if(this.userMedia.stream)this.stopUserMedia()
  }
  onError(e){
    console.error(e)
  }
}
